import { Component, OnInit } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';
import { NotificationService, BullySubjectService } from 'app/shared/service';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { DisseminationService } from '../dissemination-management.service';
import { PublicService } from 'app/public/public.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-graphic',
    templateUrl: './graphic.component.html',
    styleUrls: ['./graphic.component.css']
})
export class GraphicComponent implements OnInit {
    selectType = 0;

    search$ = new Subject<object>();
    pagination: any; // 分页数据的对象
    searchData: any; // 搜索数据的对象
    listOfData = null; // 列表数据的数组
    renderHeader = null; // 表头数据的数组
    toolbarList = [
        // 工具条栏
        // { className: 'icon-chakan' },
        // { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' }
        // { className: 'icon-screenfull' },
        // { className: 'icon-xiazai' }
    ];
    // 筛选框下拉列表
    selectionList = {
        Type: ['monochrome 1bit', 'monochrome 8bit', 'color classic', 'color 24bit']
    };
    selectGraphic = null;
    addGraphicsTitle: string;
    dataId = null;
    isVisible = false;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    graphicTypeObj = {};
    graphicTypeArr = [];
    constructor(
        private msg: NotificationService,
        private modalService: NzModalService,
        public diss: DisseminationService,
        private pub: PublicService,
        private translate: TranslateService
    ) {}

    ngOnInit() {
        const tempTranslate = {};
        Object.keys(this.diss.graphicTypeObj).forEach(key => {
            this.translate.get('DisseminationManagement.Graphics.' + key).subscribe((res: string) => {
                tempTranslate[res] = this.diss.graphicTypeObj[key];
                this.graphicTypeObj = tempTranslate;
                this.graphicTypeArr.push(res);
            });
        });
        this.searchPipeSet();
        this.renderHeader = [
            {
                name: 'ID',
                key: null,
                value: 'graphic_id',
                isChecked: true
            },
            {
                name: 'Name',
                key: null,
                value: 'graphic_name',
                isChecked: true
            },
            {
                name: 'Type',
                key: null,
                value: 'graphic_type',
                isChecked: true
            },
            {
                name: 'Height',
                key: null,
                value: 'height',
                isChecked: true
            },
            {
                name: 'Width',
                key: null,
                value: 'width',
                isChecked: true
            },
            {
                name: 'Pictogram',
                key: null,
                value: 'url',
                isChecked: true
            }
        ];
        this.initData();
        this.getData();
        this.getButtonAccess();
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('10', this.accessButton);
    }
    // 防抖函数注册
    searchPipeSet() {
        this.search$.pipe(debounceTime(1000), distinctUntilChanged()).subscribe((kw: any) => {
            this.pagination.currentPage = 1;
            this.getData();
        });
    }
    // 搜索(防抖)
    onSearch(name): void {
        this.search$.next({ name: this.searchData[name] });
    }
    // 初始化分页和搜索
    initData() {
        this.pagination = {
            totalEle: 10,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
        this.searchData = {
            graphic_id: null,
            graphic_name: null,
            graphic_type: null,
            height: null,
            url: null,
            width: null
        };
        this.listOfData = [];
    }
    // 获取数据
    getData() {
        this.selectGraphic = null;
        for (const item in this.searchData) {
            if (this.searchData.hasOwnProperty(item)) {
                if (this.searchData[item] === '') {
                    this.searchData[item] = null;
                }
            }
        }
        const params = {
            condition: this.searchData,
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.diss.getGraphicList(params).subscribe(res => {
            const content = res.data;
            if (!content) {
                this.listOfData = [];
                return;
            }
            this.listOfData = content.content;
            this.pagination.currentSize = content.numberOfElements;
            this.pagination.totalEle = content.totolElements;
        });
    }
    // 新增和编辑功能
    addOrEdit(flag) {
        if (flag === 'add') {
            this.addGraphicsTitle = 'Add_Graphics';
            this.cancelActive();
            const date = new Date();
            this.dataId = parseInt('' + date.getDate() + date.getMinutes() + date.getSeconds(), 10);
            this.isVisible = true;
        } else {
            this.addGraphicsTitle = 'Edit_Graphics';
            if (this.selectGraphic) {
                this.isVisible = true;
            } else {
                this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.select_notify' });
            }
        }
    }
    // 删除
    delete(): void {
        if (this.selectGraphic) {
            const tempTranslate = [
                { title: 'DisseminationManagement.Graphics.Delete_Equipment' },
                { title: 'DisseminationManagement.Graphics.Are you sure you want to remove this Equipment' },
                { title: 'DisseminationManagement.Graphics.Delete_Save' },
                { title: 'DisseminationManagement.Graphics.Delete_Cancel' }
            ];
            tempTranslate.forEach(item => {
                this.translate.get(item.title).subscribe((res: string) => {
                    item.title = res || '';
                });
            });
            this.modalService.confirm({
                nzTitle: '<i class="iconfont icon-delete" style="font-size:24px"></i>' + tempTranslate[0].title,
                nzContent: '<p style="font-size:24px">' + tempTranslate[1].title + '?</p>',
                nzOkText: tempTranslate[2].title,
                nzOnOk: () => {
                    this.diss.deleteGraphic(this.selectGraphic.id).subscribe(res => {
                        if (res.messagecode === '900102') {
                            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.repeat_notify' });
                        } else {
                            // 判断当前页是否有数据
                            if ((this.pagination.totalEle - 1) / this.pagination.pageSize === this.pagination.currentPage - 1) {
                                this.pagination.currentPage = 1;
                            }
                            this.getData();
                            this.selectGraphic = null;
                        }
                    });
                },
                nzCancelText: tempTranslate[3].title,
                nzOnCancel: () => {}
            });
        } else {
            this.msg.notify({ type: 'warning', path: 'EquipmentManagement.EquipmentManagement.select_notify' });
            // 提示用户没有选中项目
        }
    }
    // 刷新
    refresh(): void {
        this.cancelActive();
        this.initData();
        this.getData();
    }
    // 取消选中
    cancelActive(): void {
        this.selectGraphic = null;
        this.listOfData.forEach((data, index) => {
            data.active = false;
        });
    }
    // 点击tr取值
    clickTR(i): void {
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                this.selectGraphic = data;
            }
        });
    }
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }
    onSizeChange(e) {
        this.pagination.pageSize = e;
        const total = this.pagination.totalEle;
        const curPage = this.pagination.currentPage;
        this.pagination.currentPage = Math.ceil(total / e) < curPage ? Math.ceil(total / e) : curPage;
        this.getData();
    }
}
